import { save } from '@tauri-apps/plugin-dialog';
import { writeFile, writeTextFile, readTextFile, BaseDirectory, readDir, DirEntry, mkdir, exists } from "@tauri-apps/plugin-fs";

export const readTextFromFile = async (path: string, options: {
    baseDir?: BaseDirectory,
}): Promise<string> => {
    let content = await readTextFile(path, { ...options });
    return content;
}

export const saveDataUri2File = async (dataUri: string, options: {
    name: string,
    extensions: Array<string>
}) => {
    const path: string | null = await save({
        filters: [
            {
                name: options.name,
                extensions: options.extensions,
            },
        ],
    });
    console.log(path);
    if (path === null) {
        return;
    }
    writeFile(path, dataUri2Array(dataUri))
    // writeTextFile(path, "tssssss");
}


export const saveText2File = async (data: string, options: {
    name: string,
    extensions: Array<string>
}) => {
    const path: string | null = await save({
        filters: [
            {
                name: options.name,
                extensions: options.extensions,
            },
        ],
    });
    console.log(path);
    if (path === null) {
        return;
    }
    writeTextFile(path, data)
}

export const saveText = async (path: string, data: string) => {
    console.log(path);
    if (path === null) {
        return;
    }
    writeTextFile(path, data)
}


export const saveFile = async (data: Uint8Array, options: {
    name: string,
    extensions: Array<string>
}) => {
    const path: string | null = await save({
        filters: [
            {
                name: options.name,
                extensions: options.extensions,
            },
        ],
    });
    console.log(path);
    if (path === null) {
        return;
    }
    writeFile(path, data)
}

export const listFiles = async (path: string, filter?: (entry: DirEntry) => boolean, options?: { baseDir?: BaseDirectory, }): Promise<DirEntry[]> => {
    let res = await readDir(path, { baseDir: options?.baseDir });
    if (filter) {
        res = res.filter(filter);
    }
    console.log(res);
    return res;
}

export const createDirs = async (path: string, options?: { baseDir?: BaseDirectory, }): Promise<boolean> => {

    if (await exists(path, { baseDir: options?.baseDir })) {
        return true;
    }
    await mkdir(path, { baseDir: options?.baseDir, recursive: true, });
    return true;
}

const dataUri2Array = (dataUri: string): Uint8Array => {
    var data = dataUri.split(',')[1];
    var bytes = atob(data);
    var buf = new ArrayBuffer(bytes.length);
    var arr = new Uint8Array(buf);

    for (var i = 0; i < bytes.length; i++) {
        arr[i] = bytes.charCodeAt(i);
    }

    // arr.type = mime(dataUri);
    return arr;
};

/**
 * Return data uri mime type.
 */

export function mime(uri: string) {
    return uri.split(';')[0].slice(5);
}